package com.lej.app_main.webJs

import android.content.Intent
import android.graphics.Bitmap
import android.net.Uri
import android.util.Log
import android.webkit.JavascriptInterface
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentActivity
import androidx.lifecycle.lifecycleScope
import com.google.gson.JsonObject
import com.lej.core.common.FRAGMENT_WEB_TAG
import com.lej.core.common.PAY_BY_AIPAY
import com.lej.core.common.PAY_BY_WX
import com.lej.core.common.PCacheInfo
import com.lej.core.router.CRouter
import com.lej.core.utils.ConvertUtils
import com.lej.core.utils.extention.*
import com.lej.core.utils.urlToBitmap
import com.lej.core.webView.BaseJsInstance
import com.lej.core.webView.WebViewActivity
import com.lej.core.webView.WebViewFragment
import com.lej.dataservice.club.bean.pay.WXPayInfoData
import com.lej.pay.utils.PayUtils
import com.lej.wx.data.WXShareInfo
import com.lej.wx.data.WxStatus
import com.lej.wx.jumpMiniProgram
import com.lej.wx.shareSmallApp
import com.lej.wx.wxShareImg
import com.lej.wx.wxShareLink
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import java.util.*

/**
 * js通信接口
 */
open class HomeJavascriptInterface(
    private val activity: FragmentActivity,
    private val fragment: Fragment? = null
) :
    BaseJsInstance(activity) {
    override fun getInterfaceName() = "jsProduct"

    @JavascriptInterface
    fun closePage(tips: String) {
        if (!activity.isDestroyed) activity.finish()
    }


    @JavascriptInterface
    fun backGamePage(t:String){ //unity打开web返回
        activity.removeFragment(FRAGMENT_WEB_TAG)
    }

    @JavascriptInterface
    fun openExternalUrl(url:String){  //自带浏览器打开web
        if(url.isNullOrEmpty()) return
        val uri: Uri = Uri.parse(url)
        val intent = Intent(Intent.ACTION_VIEW, uri)
        activity.startActivity(intent)
    }

    @JavascriptInterface
    fun sharePageCard(json: String) {//分享卡片
        shareSmallApp(json)
    }

    @JavascriptInterface
    fun shareImg(data64: String) {//分享卡片
        activity.lifecycleScope.launch {
            val data = Base64.getDecoder().decode(data64.replace("\r\n", "").replace("data:image/png;base64,",""))
            activity.wxShareImg(data)
        }
    }

    @JavascriptInterface
    fun shareLink(json: String) {//分享链接
        val asJson = json.fromJson<JsonObject>() ?: return
        activity.lifecycleScope.launch {
            val data = Base64.getDecoder().decode(asJson.get("thumbUrl").asString.replace("\r\n", "").replace("data:image/png;base64,",""))
            activity.wxShareLink(asJson.get("webUrl").asString,data,asJson.get("webTitle").asString,asJson.get("webDesc").asString)
        }
    }

    @JavascriptInterface
    fun jumpMiniProgram(json: String) {//跳转小程序/小游戏
        val asJson = json.fromJson<JsonObject>() ?: return
        activity.jumpMiniProgram(asJson.get("path").asString,asJson.get("username").asString)
    }

    @JavascriptInterface
    fun intoDetail(nftId: String) {
//        activity.router(CRouter.nftDetail) {
//            withInt(NFT_ID, nftId.toInt())
//        }
    }

    private fun shareSmallApp(json: String) {
        val asJson = json.fromJson<JsonObject>() ?: return
        val info = WXShareInfo(
            title = asJson.get("title").asString,
            description = asJson.get("description").asString,
            webpageUrl = asJson.get("webpageUrl").asString,
            userName = asJson.get("userName").asString,
            path = asJson.get("path").asString,
            miniprogramType = asJson.get("miniprogramType").asInt,
            urlData = null,
            thumbData = ""
        )
        val thumbData = asJson.get("thumbData").asString
        activity.lifecycleScope.launch(Dispatchers.IO) {
            kotlin.runCatching {
                val url = "$thumbData?imageView2/1/w/400/h/320"
                val bitmap = activity.urlToBitmap(url) ?: return@launch
                val urlByte = ConvertUtils.bitmap2Bytes(bitmap, Bitmap.CompressFormat.JPEG)
                info.urlData = urlByte
                activity.shareSmallApp(info)
            }
        }
    }

    @JavascriptInterface
    fun pay(json: String) {//调起支付
        Log.d("*****", json)
        val jsonObject = json.fromJson<JsonObject>() ?: return
        val payType = jsonObject.get("pay_platform").asInt
        if (payType == PAY_BY_WX) {
            val info = jsonObject.fromJsonObject<WXPayInfoData>() ?: return
            PayUtils.wxPay(
                context = activity,
                appId = info.appId,
                partnerId = info.partnerId,
                prepayId = info.prepayId,
                noncestr = info.nonceStr,
                timestamp = info.timeStamp,
                paySign = info.paySign
            ) { status, msg ->
                loadJs(
                    when (status) {
                        WxStatus.WX_OK -> "javascript:window.handlePaySuccess()"
                        WxStatus.WX_CANCEL -> "javascript:window.handlePayCancel()"
                        WxStatus.WX_ERROR -> "javascript:window.handlePayFail(\"${msg}\")"
                    }
                )
            }
        } else if (payType == PAY_BY_AIPAY) {
        }
    }

    @JavascriptInterface
    fun transfer(json: String) {//转让房间(分享)
        shareSmallApp(json)
    }

    @JavascriptInterface
    fun house(id: Int) {//进入3d空间
        "功能开发中，敬请期待~".toast()
//        activity.router(CRouter.unityhouse) {
//            withInt(UnityRoomId, id)
//            withInt(UnityRoomType, UnityMiniGameFrom.LookRoom)
//        }
    }

    @JavascriptInterface
    fun login(tips: String) {//跳转登录
        activity.router(CRouter.login)
    }

    @JavascriptInterface
    fun skipPage(json: String) {
        val jsonObject = json.fromJson<JsonObject>() ?: return
        val url = jsonObject.get("url").asString
        val showNav = jsonObject.get("showNav").asInt
        val showTitle = showNav == 1
        activity.toLink(url, showTitle = showTitle)
    }

    fun setToken() {
        loadJs("javascript:window.setToken(\"${PCacheInfo.userToken()}\")")
    }

    private fun loadJs(js: String) {
        (activity as? WebViewActivity)?.loadJs(js)
            ?: (fragment as? WebViewFragment)?.loadJs(js)
    }
}

